<template>
  <div>
    <el-dialog
      :title="jobInfo._id?'修改职位':'添加职位'"
      v-model="isShow"
      width="500"
      center
      @close="closeDiglog"
      @open="openDialog"
    >
      <el-form :model="jobInfo" :rules="rules" ref="formRef">
        <el-form-item label="职位名称:" prop="jobName">
          <el-input
            placeholder="请输入职位名称"
            v-model="jobInfo.jobName"
          ></el-input>
        </el-form-item>
        <el-form-item label="职位描述:" prop="jobContent">
          <el-input
            placeholder="请输入职位描述"
            type="textarea"
            v-model="jobInfo.jobContent"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDiglog">取消</el-button>
          <el-button type="primary" @click="AddOrUpdateJob"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
defineOptions({
  name: "AddJob",
});
import { AddOrUpdateJobAPI, getJobDetailAPI } from "@/api/job";
import { ElMessage } from "element-plus";
import { ref, reactive, watch } from "vue";
const props = defineProps(["modelValue", "jobId"]);
const emits = defineEmits(["update:modelValue", "getJobList", "update:jobId"]);
let isShow = ref(props.modelValue);
let jobInfo = reactive({
  jobName: "",
  jobContent: "",
});
let formRef = ref(null);
let rules = reactive({
  jobName: [
    { required: true, message: "请输入职位名称", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  jobContent: [
    { required: true, message: "请输入职位描述", trigger: "blur" },
    { min: 2, max: 150, message: "长度在 2 到 150 个字符", trigger: "blur" },
  ],
});
watch(
  () => props.modelValue,
  (newValue) => {
    isShow.value = newValue;
    emits('update:modelValue', isShow.value)
  }
);
watch(()=>props.jobId,(newValue)=>{
  jobInfo._id = newValue
  emits('update:jobId', jobInfo._id)
})
const getJobDetail = async ()=>{
  if(jobInfo._id) {
    let result = await getJobDetailAPI(jobInfo._id)
    if(result.code == 200) {
      Object.assign(jobInfo,result.data)
    }
  }
}
const closeDiglog = () => {
  isShow.value = false;
  jobInfo._id = ''
  emits('update:jobId','')
  emits("update:modelValue", false);
};
const openDialog = () => {
  formRef.value.resetFields();
  getJobDetail()
};
const AddOrUpdateJob = async () => {
  await formRef.value.validate();
  let result = await AddOrUpdateJobAPI(jobInfo);
  if (result.code == 200) {
    ElMessage.success(jobInfo._id ? "修改成功" : "添加成功");
    emits("getJobList");
    closeDiglog();
  }
};
</script>

<style lang="scss" scoped></style>
